//
//  WBOauthViewModel.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/5.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOauthViewModel: NSObject {
    
    
    /// MVVM 原则:1.一个View对应一个ViewModel 一个ViewModel对应一个Model
    //         2.ViewController 不要直接和Model关联
    
    //定义用户属性类
    var userAccount: WBUserAccount?
    
    
    //创建WBOauthViewModel的单例 因为在其他类都需要使用这个类 拿到Token
    static let shareInstance:WBOauthViewModel = WBOauthViewModel()
    
    //设置bool属性类判断Token是否为空 (如果不为空是登录过的)
    var islogin: Bool{
        
        get{
            return userAccount?.access_token != nil
        }
    }
    
    //经常用到Token 所以定义一个属性 供其他类调用就好
    var access_token:String? {
        
        return userAccount?.access_token
        
    }
    
    
    //重写init初始化方法让 userAccount去读取数据
    private override init() {
        super.init()
        //记得调用super init
        userAccount = WBUserAccount.readUserAccount()
    }
    
    //MARK: --第二步 通过AFN 将code 发送给服务器来换取Token
    //通过闭包传递获取到Token
     func loadToken(code:String, suess:()->(),failed:()->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        /*
        必选	类型及范围	说明
        client_id	true	string	申请应用时分配的AppKey。
        client_secret	true	string	申请应用时分配的AppSecret。
        grant_type	true	string	请求的类型，填写authorization_code
        
        grant_type为authorization_code时
        必选	类型及范围	说明
        code	true	string	调用authorize获得的code值。
        redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
        */
        let parameters = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type":"authorization_code",
            "code": code,
            "redirect_uri":AppRedictUrl
        ]
        
        //通过pOST请求
        WBHTTPClient.shareInstance.request( .POST, URLString: urlString, parameters: parameters, success: { (_ , JSON) -> Void in
            
           // printLog(JSON)
            
            if  let json = JSON as? [String:AnyObject] {
                
                let model = WBUserAccount(dic: json)
                
                //printLog("输出获取到的Token-----\(model.access_token)")
                
                //获取到Token之后再进行数据请求来获取用户信息
                self.loadInfo(model, success:suess, failed:failed)
                //用户信息
                /*
                "access_token" = "2.00VGylnB0vjiam9b21ae6a2epA7LxD";
                "expires_in" = 132650;
                "remind_in" = 132650;
                uid = 1651605755;
                */
            }
            
            //错误日志输出
            }) { (_ , error) -> Void in
                
                printLog(error)
                
                failed() //失败返回
                
        }
    }
    
    
    //MARK:-- 第三步:通过获取的Token 来获取用户的信息
   private func loadInfo(model:WBUserAccount,success:()->(),failed:()->()) {
        //guard在条件不满足时会跳出
        guard let uid = model.uid, token = model.access_token else {
            
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let paramas = ["access_token":token,
            "uid": uid
        ]
        //网络请求
        WBHTTPClient.shareInstance.request(.GET, URLString: urlString, parameters: paramas, progress: nil, success: { (_ , JSON) -> Void in
           // printLog(JSON)
            
            if let json = JSON as? [String:AnyObject]{
                
                let name = json["screen_name"]as? String
                model.screen_name = name
                
                model.profile_image_url = json["profile_image_url"]as? String
                
//                printLog(model.profile_image_url)
                
                //进行归档
                //1.获取沙盒路径
                let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
                
//                printLog(path)
                
                //2.拼接文件的路径
                let filePath = (path as NSString).stringByAppendingPathComponent("info.cxj")
                //归档
                NSKeyedArchiver.archiveRootObject(model, toFile: filePath)
                
                //给userAccount赋值
                self.userAccount = model
                
                //授权成功让视图消失 调用闭包 切换控制器
                success()
              }
            
            }) { (_ , erorr) -> Void in
                printLog(erorr)
                 failed() //错误
        }
    }
}
